<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Cache;
use app\admin\model\Menu as MenuModel;
/**
 * 后台节点控制器
 * @author 唐小虎 <1731050423@qq.com>
 */
class Menu extends Base {
	/**
     * 后台节点首页
     * @author 唐小虎 <1731050423@qq.com>
     */
    public function index()
    {
    	cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 获取节点数据
        $data_list = MenuModel::getMenusByGroup();
        // $max_level = $this->request->get('max', 0);
        $menus = $this->getNestMenu($data_list);
        $this->assign('menus',$menus);
        $this->assign('meta_title','节点管理');
        return $this->fetch();
    }

    /**
     * 添加
     */
    public function add(){
    	// 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Menu');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            // 顶部节点url检查
            // if ($data['pid'] == 0 && $data['url'] == '' ) {
            //     $this->error('顶级节点的节点链接不能为空');
            // }
            if ($menu = MenuModel::create($data)) {
                // Cache::clear();
                // 记录行为
                action_log('add_menu', 'menu', $menu['id'], UID);
                $this->success('新增成功', cookie('__forward__'));
            } else {
                $this->error('新增失败');
            }
        }
        $this->assign('menu',MenuModel::getMenuTree(0, '', ''));
        $this->assign('meta_title', '添加节点');
        return $this->fetch();
    }

    /**
     * 编辑节点
     * @param int $id 节点ID
     * @author 唐小虎 <1731050423@qq.com>
     * @return mixed
     */
    public function edit($id = 0)
    {
        if ($id === 0) $this->error('缺少参数');
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Menu');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            if (MenuModel::update($data)) {
                Cache::clear();
                // 记录行为
                // $details = '节点ID('.$id.')';
                action_log('update_menu', 'menu', $id, UID);
                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败', cookie('__forward__'));
            }
        }
        $this->assign('meta_title', '编辑节点');
        // 获取数据
        $info = MenuModel::get($id);
        $this->assign('info',$info);
        $this->assign('menu',MenuModel::getMenuTree(0, '', ''));
        return $this->fetch();
    }

    /**
     * 删除节点
     * @param array $record 行为日志内容
     * @author 唐小虎 <1731050423@qq.com>
     * @return mixed
     */
    public function delete($record = [])
    {
        $id = $this->request->param('id');
        $menu = MenuModel::where('id', $id)->find();

        if ($menu['system_menu'] == '1')  return $this->error('系统节点，禁止删除');

        // 获取该节点的所有后辈节点id
        $menu_childs = MenuModel::getChildsId($id);

        // 要删除的所有节点id
        $all_ids = array_merge([(int)$id], $menu_childs);

        // 删除节点
        if (MenuModel::destroy($all_ids)) {
            Cache::clear();
            // 记录行为
            // $details = '节点ID('.$id.'),节点标题('.$menu['title'].'),节点链接('.$menu['url_value'].')';
            action_log('update_menu', 'menu', $id, UID);
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

    /**
     * 获取嵌套式节点
     * @param array $lists 原始节点数组
     * @param int $pid 父级id
     * @param int $max_level 最多返回多少层，0为不限制
     * @param int $curr_level 当前层数
     * @author xiaohu <1731050423@qq.com>
     * @return string
     */
    private function getNestMenu($lists = [], $max_level = 0, $pid = 0, $curr_level = 1)
    {
        $result = '';
        foreach ($lists as $key => $value) {
            if ($value['pid'] == $pid) {
                $disable  = $value['status'] == 0 ? 'dd-disable' : '';

                // 组合节点
                $result .= '<li class="dd-item" data-id="'.$value['id'].'">';
                $result .= '<div class="dd-handle">';
                if ($value['icon'] != '') {
                	$result .= '<span class="label label-info"><i class="'.$value['icon'].'"></i></span>'.$value['title'];
                }else{
                	$result .= '<span class="label label-info"><i class="fa fa-circle-o"></i></span>'.$value['title'];
                }
                if ($value['url'] != '') {
                    $result .= '<span style="margin-left:20px;" class="label label-info"><i class="fa fa-link"></i> '.$value['url'].'</span>';
                }
                $result .= '<span class="pull-right">';
                $result .= '<a href="'.url('add', ['pid' => $value['id']]).'" data-toggle="tooltip" data-original-title="新增子节点"><i class="list-icon fa fa-plus fa-fw"></i></a><a href="'.url('edit', ['id' => $value['id']]).'" data-toggle="tooltip" data-original-title="编辑"><i class="list-icon fa fa-pencil fa-fw"></i></a>';
                if ($value['status'] == 0) {
                    // 启用
                    $result .= '<a href="javascript:void(0);" data-ids="'.$value['id'].'" class="enable" data-toggle="tooltip" data-original-title="启用"><i class="list-icon fa fa-check-circle-o fa-fw"></i></a>';
                } else {
                    // 禁用
                    $result .= '<a href="javascript:void(0);" data-url="'.url('disable', ['ids' => $value['id'], 'table' => 'menu']).'" data-ids="'.$value['id'].'" class="disable" data-toggle="tooltip" data-original-title="禁用"><i class="list-icon fa fa-ban fa-fw"></i></a>';
                }
                $result .= '<a data-url="'.url('delete', ['id' => $value['id'], 'table' => 'menu']).'" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></span>';
                $result .= '</span>';
                $result .= '</div>';

                if ($max_level == 0 || $curr_level != $max_level) {
                    unset($lists[$key]);
                    // 下级节点
                    $children = $this->getNestMenu($lists, $max_level, $value['id'], $curr_level + 1);
                    if ($children != '') {
                        $result .= '<ol class="dd-list">'.$children.'</ol>';
                    }
                }

                $result .= '</li>';
            }
        }
        return $result;
    }
}
